package org.mspring.mlog.web.freemarker.directive;

import java.io.IOException;
import java.util.Map;

import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.mlog.utils.WebUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.freemarker.DirectiveUtils;
import org.mspring.platform.web.freemarker.directive.AbstractDirectiveModel;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 用于获取用户图像
 * 
 * @author Gao Youbo
 * @since 2013年7月12日
 */
public class UserAvatarDirectiveModel extends AbstractDirectiveModel {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void exec(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        // TODO Auto-generated method stub
        String result = null;
        String avatar = DirectiveUtils.getString("avatar", params);
        Long user = DirectiveUtils.getLong("user", params);
        if (StringUtils.isNotBlank(avatar)) {
            result = WebUtils.getContextPath() + UploadUtils.UPLOAD_FOLDER + avatar;
        } else if (user != null) {
            User u = ServiceFactory.getUserService().get(user);
            if (u != null && StringUtils.isNotBlank(u.getSmallAvatar())) {
                result = WebUtils.getContextPath() + UploadUtils.UPLOAD_FOLDER + u.getSmallAvatar();
            }
        }

        if (result == null) {
            result = WebUtils.getContextPath() + "/images/default_avatar.png";
        }
        env.getOut().append(result);
    }

}
